/**
 * Copyrights Christophe Cornu 2010, All rights reserved.
 */
package com.cctl.speaker;

import java.util.Map;

/**
 * Efficient representation of a sentence
 * Each word is a reference to a string in a given
 * dictionary if that dictionary contains that string - this allows
 * for quick string matching by reference.
 */
public class Sentence {
	public String[] words;
	Map<String, String> dictionary;
	
	public Sentence(String[] words, Map<String, String> dictionary, boolean updateDictionary) {
		this.words = new String[words.length];
		this.dictionary = dictionary;
		for (int i = 0; i < words.length; i++) {
			String word = words[i];
			String found = dictionary.get(word);
			if (found == null) {
				if (!updateDictionary) {
					this.words[i] = word;
					continue;
				}
				// Add to dictionary
				dictionary.put(word, word);
				found = word;
			}
			if (found == null)
				throw new IllegalArgumentException();
			this.words[i] = found;
		}
	}
	
	/**
	 * Clone the given sentence, with every word set to lower case
	 * (remove accents) if <code>simplify</code> is <code>true</code>.
	 */
	public Sentence(Sentence source, boolean simplify) {
		words = new String[source.words.length];
		if (!simplify) {
			System.arraycopy(source.words, 0, words, 0, source.words.length);
			return;
		}
		for (int i = 0; i < words.length; i++) {
			String simplified = source.words[i].toLowerCase();
			String found = source.dictionary.get(simplified);
			words[i] = found != null ? found : simplified;
		}
	}
	
	@Override
	public String toString() {
		String result = "";
		for (int i = 0; i < words.length; i++)
			result += words[i] + " ";
		return result;
	}
	
	public int countLetters() {
		int result = 0;
		for (String word : words)
			result += word.length();
		return result;
	}
}
